package info.wegosoft.android.adapter;

import info.wegosoft.R;
import info.wegosoft.android.activity.DetailMBlogActivity;
import info.wegosoft.android.model.MBlog;
import info.wegosoft.android.model.Platform;
import info.wegosoft.android.util.TimeUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources.NotFoundException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

/**
 * 
 * Filename:    MBlogArrayAdapter.java 
 * Package:     info.wegosoft.android.adapter 
 * Description: TODO(这里用一句话描述这个类的作用)
 * Copyright:   Copyright (c) wegosoft.info 2011  
 * @author:     李辉 
 * email:       fzlihui@gmail.com
 * @version:    1.0  
 * Create at:   2011-5-13 下午03:46:39
 */
public class MBlogArrayAdapter extends BaseAdapter {

	private int resource;
	private Context context;
	private List<MBlog> mBlogList;
	private Map<String, Bitmap> faceBitmapsMap;
	private Map<String, Bitmap> microBlogImageBitmapsMap;
	private Map<String, Bitmap> remicroBlogImageBitmapsMap;
	private String addCacheFlag;  //加在cache名字中的代号，sina tencent
	private static final String THUMBNAIL_IMAGES_CACHE_DIR = "thumbnail";
	
	public MBlogArrayAdapter(Context context, int resource,
			List<MBlog> mBlogList,int platformType) {

		this.resource = resource;
		
		this.context = context;
		
		this.mBlogList = mBlogList;
		
		faceBitmapsMap = new HashMap<String, Bitmap>();
		
		microBlogImageBitmapsMap = new HashMap<String, Bitmap>();
		
		remicroBlogImageBitmapsMap = new HashMap<String, Bitmap>();
		
		switch(platformType){
		
			case Platform.SINA_PLATFORM:
				
				 addCacheFlag = "sina";
				 
				 break;
				 
			case Platform.TENCENT_PLATFORM:
				
				 addCacheFlag = "tencent";
				 
				 break;
				 
			default:
				
				 break;
		}
		
		// 开启一个线程刷新图片
		new UpdateImagesThread().start();
	}

	public int getCount() {
		
		return mBlogList.size();
		
	}

	public Object getItem(int position) {
		
		return mBlogList.get(position);
		
	}

	public long getItemId(int position) {
		
		return position;
		
	}
	
	private class UpdateImagesThread extends Thread {
		@Override
		public void run() {
			
			for (MBlog mBlog : mBlogList) {
				
				try {
					
					MBlogArrayAdapter.this.initBitmap(mBlog);
					
				} catch (NotFoundException e) {
					
					e.printStackTrace();
					
				} catch (IOException e) {
					
					e.printStackTrace();
					
				}
			}
		}
	}

	/**
	 * 刷新数据方法
	 * 
	 * @param mBlogList
	 */
	public void update(List<MBlog> mBlogList) {
		
		this.mBlogList = mBlogList;
		
		this.notifyDataSetChanged();
		
		// 开启一个线程刷新图片
		new UpdateImagesThread().start();
		
	}

	/**
	 * 初始化图片缓存
	 * 
	 * @throws NotFoundException
	 * @throws IOException
	 */
	private void initBitmap(MBlog mBlog) throws NotFoundException,
			IOException {
		// 头像格式http://tp1.sinaimg.cn/1252373132/50/1290081552/1
		// 不能用faceImage.setImageURI(new
		// Uri.Builder().encodedPath(mBlog.getUser().getProfile_image_url()).build());
		// Uri只能是本机资源
		InputStream faceImageUrlStream = null;
		
		InputStream microBlogImageUrlStream = null;
		
		InputStream retweeted_statusUrlStream = null;
		
		Bitmap faceBitmap = null;
		
		Bitmap microBlogImageBitmap = null;
		
		Bitmap retweeted_status_microBlogImageBitmap = null;
		
		FileOutputStream out = null;
		
		FileInputStream in = null;
		

		// 头像,先判断本地是否有缓存，没有再下载头像

		// System.out.println(context.getResources().getString(
		// R.string.face_cache_prefix) + addCacheFlag
		// + mBlog.getUser_id() + ".jpeg");
		// 由于腾讯获取不到uid，只能用唯一的账户名做标志
		// in = context.openFileInput(context.getResources().getString(
		// R.string.face_cache_prefix) + addCacheFlag
		// + mBlog.getName() + ".jpeg");
		File faceFile = new File(Environment.getExternalStorageDirectory()
				+ context.getResources().getString(R.string.user_face_dir_path)
				+ addCacheFlag + "/" + mBlog.getName() + ".jpeg");

		// 本地头像缓存存在
		if (faceFile.exists()) {

			in = new FileInputStream(faceFile);

			faceBitmap = BitmapFactory.decodeStream(in);

		// 本地缓存中不存在这个头像再下载并缓存到本地
		} else {

			// 有可能腾讯微博头像是默认的，此时mBlog.getHead()为空，就用默认的face
			if (mBlog.getHead() != null && !mBlog.getHead().trim().equals("")) {

				URL faceImageUrl = new URL(mBlog.getHead());

				faceImageUrlStream = faceImageUrl.openStream();

				faceBitmap = BitmapFactory.decodeStream(faceImageUrlStream);

				//要先将路径上所有文件夹创建好
				File dir = new File(Environment.getExternalStorageDirectory()
						+ context.getResources().getString(R.string.user_face_dir_path)
						+ addCacheFlag);
				
				if(!dir.exists())
					dir.mkdirs();
					
				//返回true表示原来这个文件不存在
				if (faceFile.createNewFile()) {

					out = new FileOutputStream(faceFile);

					faceBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);

				}

				// 以用户id缓存头像
				// out = context.openFileOutput(
				// context.getResources().getString(
				// R.string.face_cache_prefix) + addCacheFlag
				// + mBlog.getName() + ".jpeg",
				// Context.MODE_PRIVATE);

			}

		}

		faceBitmapsMap.put(mBlog.getName(), faceBitmap);

		// 状态包含的图片,先判断本地是否有缓存，没有再下载
		if (mBlog.getThumbnail_pic() != null && !mBlog.getThumbnail_pic().trim().equals("")) {

			// in = context.openFileInput(context.getResources().getString(
			// R.string.status_image_cache_prefix) + "thumbnail_" + addCacheFlag
			// + mBlog.getId() + ".jpeg");

			File picFile = new File(Environment.getExternalStorageDirectory()
					+ context.getResources().getString(
							R.string.mblog_images_dir_path) + addCacheFlag
					+ "/" + THUMBNAIL_IMAGES_CACHE_DIR + "/" + mBlog.getId() + ".jpeg");

			// 本地存在图片缓存
			if (picFile.exists()) {

				in = new FileInputStream(picFile);

				microBlogImageBitmap = BitmapFactory.decodeStream(in);

			// 本地不存在图片缓存
			} else {

				// 本地不存在缓存，下载并缓存到本地
				URL microBlogImageUrl = new URL(mBlog.getThumbnail_pic());

				microBlogImageUrlStream = microBlogImageUrl.openStream();

				microBlogImageBitmap = BitmapFactory
						.decodeStream(microBlogImageUrlStream);

				//要先将路径上所有文件夹创建好
				File dir = new File(Environment.getExternalStorageDirectory()
						+ context.getResources().getString(
								R.string.mblog_images_dir_path) + addCacheFlag
						+ "/" + THUMBNAIL_IMAGES_CACHE_DIR);
				
				if(!dir.exists())
					dir.mkdirs();
				
				if (picFile.createNewFile()) {

					out = new FileOutputStream(picFile);

					microBlogImageBitmap.compress(Bitmap.CompressFormat.JPEG,
							100, out);

				}
				// 将状态包含的图片以状态id为名称缓存
				// out = context.openFileOutput(
				// context.getResources().getString(
				// R.string.status_image_cache_prefix) + "thumbnail_" +
				// addCacheFlag
				// + mBlog.getId() + ".jpeg",
				// Context.MODE_PRIVATE);

			}
							
		}
		microBlogImageBitmapsMap.put(mBlog.getId(), microBlogImageBitmap);

		// 是否存在转发的原状态
		if (mBlog.getSourceMBlog() != null) {
			
			//原状态是否包含图片,先判断本地是否有缓存，没有再下载
			if (mBlog.getSourceMBlog().getThumbnail_pic() != null && !mBlog.getSourceMBlog().getThumbnail_pic().trim().equals("")) {

				File sourcePicFile = new File(
						Environment.getExternalStorageDirectory()
								+ context.getResources().getString(
										R.string.mblog_images_dir_path)
								+ addCacheFlag + "/" + THUMBNAIL_IMAGES_CACHE_DIR + "/"
								+ mBlog.getSourceMBlog().getId() + ".jpeg");

				// 本地存在原状态的缓存图片
				if (sourcePicFile.exists()) {

					in = new FileInputStream(sourcePicFile);

					// in = context.openFileInput(context.getResources()
					// .getString(R.string.status_image_cache_prefix) +
					// addCacheFlag
					// + mBlog.getSourceMBlog().getId() + ".jpeg");

					retweeted_status_microBlogImageBitmap = BitmapFactory
							.decodeStream(in);

				// 本地不存在原状态的缓存图片
				} else {
					// 本地不存在缓存，下载并缓存到本地
					URL retweeted_status_microBlogImageUrl = new URL(mBlog
							.getSourceMBlog().getThumbnail_pic());

					retweeted_statusUrlStream = retweeted_status_microBlogImageUrl
							.openStream();

					retweeted_status_microBlogImageBitmap = BitmapFactory
							.decodeStream(retweeted_statusUrlStream);

					File dir = new File(Environment.getExternalStorageDirectory()
							+ context.getResources().getString(
									R.string.mblog_images_dir_path)
							+ addCacheFlag + "/" + THUMBNAIL_IMAGES_CACHE_DIR);
					
					if(!dir.exists())
						dir.mkdirs();
					
					// 将状态包含的图片以状态id为名称缓存
					if (sourcePicFile.createNewFile()) {
						// out = context.openFileOutput(context.getResources()
						// .getString(R.string.status_image_cache_prefix) +
						// addCacheFlag
						// + mBlog.getSourceMBlog().getId() + ".jpeg",
						// Context.MODE_PRIVATE);

						out = new FileOutputStream(sourcePicFile);

						retweeted_status_microBlogImageBitmap.compress(
								Bitmap.CompressFormat.JPEG, 100, out);

					}
				}

				remicroBlogImageBitmapsMap.put(
						mBlog.getSourceMBlog().getId(),
						retweeted_status_microBlogImageBitmap);
			}		
		}
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		
		MBlog mBlog = (MBlog) getItem(position);
		
		RelativeLayout tableView = null;
		
		if (convertView == null) {
			
			tableView = new RelativeLayout(context);

			String inflater = Context.LAYOUT_INFLATER_SERVICE;

			LayoutInflater vi = (LayoutInflater) context.getSystemService(
					inflater);

			vi.inflate(resource, tableView, true);

		} else {
			
			tableView = (RelativeLayout) convertView;
		
		}

		try {
			
			this.putDataIntoView(tableView, mBlog, position);
		
		} catch (IOException e) {
			
			e.printStackTrace();
			
		}

		return tableView;
	}

	private void putDataIntoView(RelativeLayout tableView, final MBlog mBlog,
			int position) throws IOException {
		
		// 这里一定要先清空图片，因为在滚动list的过程中会反复读取数据，可能导致图片出现在错误位置！
		ImageView faceImage = (ImageView) tableView
				.findViewById(R.id.profile_image);
		
		faceImage.setImageResource(R.drawable.face);
		
		TextView screen_name = (TextView) tableView
				.findViewById(R.id.screen_name);
		
		TextView created_at = (TextView) tableView
				.findViewById(R.id.created_at);
		
		TextView from = (TextView) tableView.findViewById(R.id.from);
		
		TextView postCount = (TextView) tableView.findViewById(R.id.postCount);
		
		TextView text = (TextView) tableView.findViewById(R.id.text);
		
		ImageView microBlogImage = (ImageView) tableView
				.findViewById(R.id.microBlogImage);
		
		microBlogImage.setImageResource(R.drawable.loading);
		
		TextView retweeted_status_text = (TextView) tableView
				.findViewById(R.id.retweeted_status_text);
		
		ImageView retweeted_status_microBlogImage = (ImageView) tableView
				.findViewById(R.id.retweeted_status_microBlogImage);
		
		retweeted_status_microBlogImage.setImageResource(R.drawable.loading);

		// 用户头像。先判断头像下载好了没，没有用系统默认头像
		Bitmap faceImageBitmap = faceBitmapsMap.get(mBlog.getName());
		
		if (faceImageBitmap != null) {
			
			faceImage.setImageBitmap(faceImageBitmap);
			
		} 

		// 昵称
		screen_name.setText(mBlog.getScreen_name());
		
		// 状态发布时间与当前时间的相差时间
		created_at.setText(TimeUtil.timeBetween(mBlog.getCreated_at(),new Date()));
		
		// 微博来源
		from.setText(Html.fromHtml("来自：" + mBlog.getFrom()));
		
		// 转发数
		postCount.setText("转发数");
		
		// 状态内容
		text.setText(Html.fromHtml(mBlog.getText()));
		
		// 状态包含的图片。先判断下载好了没，没有用loading标志代替
		if (mBlog.getThumbnail_pic() != null && !mBlog.getThumbnail_pic().trim().equals("")) {
			
			microBlogImage.setVisibility(View.VISIBLE);
			
			Bitmap microBlogImageBitmap = microBlogImageBitmapsMap.get(mBlog
					.getId());
			
			if (microBlogImageBitmap != null) {
				
				microBlogImage.setImageBitmap(microBlogImageBitmap);
			
			}
		
		}else{
			
			microBlogImage.setVisibility(View.GONE);
			
		}

		LinearLayout ll = (LinearLayout) tableView.findViewById(R.id.retweeted_status_ll);
		
		// 回复的原状态
		if (mBlog.getSourceMBlog() != null && mBlog.getSourceMBlog().getId()!=null && !mBlog.getSourceMBlog().getId().trim().equals("")) {	
			
			ll.setVisibility(View.VISIBLE);
			
			if(mBlog.getSourceMBlog().getText() != null && !mBlog.getSourceMBlog().getText().trim().equals(""))
			{
				
				retweeted_status_text.setVisibility(View.VISIBLE);
				
				retweeted_status_text.setText(Html.fromHtml("@" + mBlog.getSourceMBlog().getScreen_name() + "：" + mBlog.getSourceMBlog().getText()));
			
			}else{
				
				retweeted_status_text.setVisibility(View.GONE);
				
			}
			
			// 原状态的图片。先判断下载好了没，没有用loading标志代替			
			if (mBlog.getSourceMBlog().getThumbnail_pic() != null && !mBlog.getSourceMBlog().getThumbnail_pic().trim().equals("")) {
				
				retweeted_status_microBlogImage.setVisibility(View.VISIBLE);
				
				Bitmap remicroBlogImageBitmap = remicroBlogImageBitmapsMap
				.get(mBlog.getSourceMBlog().getId());
				
				if (remicroBlogImageBitmap != null) {
					
					retweeted_status_microBlogImage
					.setImageBitmap(remicroBlogImageBitmap);
					
				}
				
			}else{
				
				retweeted_status_microBlogImage.setVisibility(View.GONE);
				
			}
		} else {
			
			ll.setVisibility(View.GONE);
			
			retweeted_status_text.setVisibility(View.GONE);
			
			retweeted_status_microBlogImage.setVisibility(View.GONE);
			
		}

		//跳转到微博详细内容
		tableView.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				
				Intent intent = new Intent(context,DetailMBlogActivity.class);
				
				Bundle bundle = new Bundle();
				
				bundle.putSerializable("mblog", mBlog);
				
				intent.putExtras(bundle);
				
				context.startActivity(intent);
				
			}
		});
	}


}
